<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-20
 * Time: 9:01
 */

namespace app\api\controller\v1;
use app\common\controller\Api;
use app\common\logic\OrderLogic;
use think\Log;
class Notify extends Api
{
    protected $authenticate = ['only'=>'index'];
    
    /**
     * 微信支付通知
     */
    public function wxpay(){
        
        $pay = new \Pay\Pay(config('thirdaccount.pay_wechat_pub'));
        $verify = $pay->driver('wechat')->gateway('mp')->verify(file_get_contents('php://input'));
        
        $payback = json_encode($verify);
        $fileName = "wxpay.txt";
        $file = fopen( $fileName,"a+");
        $content = $payback;
        fwrite($file, $content."\r\n");
        fclose($file);
        
        if ($verify) {
            file_put_contents('wxpay.txt', "收到来自微信的异步通知\r\n", FILE_APPEND);
            file_put_contents('wxpay.txt', "订单单号：{$verify['out_trade_no']}\r\n", FILE_APPEND);
            file_put_contents('wxpay.txt', "订单金额：".($verify['total_fee']/100)."\r\n\r\n", FILE_APPEND);
        } else {
            file_put_contents('wxpay.txt', "收到异步通知\r\n", FILE_APPEND);
        }
        
        $returnData = ['return_code'=>'SUCCESS','return_msg'=>'OK'];
        $xmlStr = $this->toXml($returnData);
        
        echo $xmlStr;
        
        $this->call($verify['out_trade_no'],'wx');
        
    
    }
    
    public function call($out_trade_no,$channel){
        
        switch ($channel){
            case 'wx':
                break;
            case 'ali':
                break;
            default:
                Log::error('支付回调错误:-out_trade_no'.$out_trade_no);
                die;
                break;
        }
        
        $orderLogic = new OrderLogic();
        $orderLogic->callOrder($out_trade_no,$channel);
        
        
    }
    

    
    /**
     * 转为XML数据
     * @param array $data 源数据
     * @return string
     */
    protected function toXml($data)
    {
        if (!is_array($data) || count($data) <= 0) {
            throw new InvalidArgumentException('convert to xml error!invalid array!');
        }
        $xml = '<xml>';
        foreach ($data as $key => $val) {
            $xml .= is_numeric($val) ? '<' . $key . '>' . $val . '</' . $key . '>' : '<' . $key . '><![CDATA[' . $val . ']]></' . $key . '>';
        }
        
        return $xml . '</xml>';
    }
    
}